package com.sanri.tools.modules.mock.l7.websocket.chat.service.ws.message;

import com.alibaba.fastjson.JSON;
import com.sanri.tools.modules.core.security.UserService;
import com.sanri.tools.modules.core.security.dtos.ThinUser;
import com.sanri.tools.modules.core.utils.SnowflakeIdWorker;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.Message;
import com.sanri.tools.modules.mock.l7.websocket.chat.service.ws.ChatSession;
import com.sanri.tools.modules.mock.l7.websocket.chat.service.ws.ChatSupport;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component("chat/bind")
@Slf4j
public class BindMessageHandler implements SocketMessageCommand.MessageHandler {
    @Autowired(required = false)
    private UserService userService;
    @Autowired
    private ChatSupport chatSupport;

    @Override
    public void handle(WebSocket conn, String message) throws IOException {
        BindMessage bindMessage = JSON.parseObject(message, BindMessage.class);

        ThinUser thinUser = userService.user(bindMessage.token);
        String username = thinUser.getToolUser().getUsername();
        log.info("登录成功: {}", username);

        ChatSession chatSession = new ChatSession(conn, thinUser);
        chatSession.setToken(bindMessage.getToken());
        ChatSupport.sessionMap.put(username, chatSession);

        // 广播上线消息
        Message chatMessage = new Message();
        chatMessage.setId(SnowflakeIdWorker.getSnowflakeId());
        chatMessage.setType("text");
        chatMessage.setFromContactId("system");
        chatMessage.setContent(username+" 登录");
        chatMessage.setSendTime(new Date().getTime());
        chatSupport.boardcastToContacts(username,chatMessage);
    }

    @Data
    public static final class BindMessage{
        private String command;
        private String token;
    }
}
